import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/storage'
import { resetRouter } from '@/router'
import { useTagsViewStore } from '@/store/tagsView'
import { getCookie, rewriteRequest, saveServCookie } from '@/api/user'
import { getUserInfo, login, logout } from '@/api/auth'
import jsCookie from 'js-cookie'
import { formatCookies } from '@/utils'

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      temuDialog: false,
      temuDialogTitle: '',
      temuShowClose: false,
      token: getToken(), // 登录信息
      userInfo: {}, // pdd用户信息
      hasPddUser: false,
      sysUser: {},
      roles: [], // 权限
      currentMall: '',
      validTokenTimer: null
    }
  },
  actions: {
    showTemuDialog(title, temuShowClose) {
      this.temuDialogTitle = title
      this.temuShowClose = temuShowClose
      this.temuDialog = true
    },
    hideTemuDialog() {
      this.temuDialog = false
    },
    pddAuth() {
      // const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        getCookie()
          .then((res) => {
            const cookies = formatCookies(res.cookies)
            Object.keys(cookies).forEach((k) => {
              k && jsCookie.set(k, cookies[k])
              // if (k === 'SUB_PASS_ID') {
              //   this.token = cookies[k]
              //   setToken(cookies[k])
              // }
            })
            resolve()
          })
          .catch((e) => {
            reject(e)
          })
      })
    },
    login(data) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        try {
          const { cookies: cs } = await login(data)
          this.token = cs
          setToken(cs)
          sessionStorage.setItem('_TEMU_NOTIFICATION_', '1')
          await saveServCookie(cs)
          const cookies = formatCookies(cs)
          Object.keys(cookies).forEach((k) => {
            k && jsCookie.set(k, cookies[k])
          })
          // await this.pddAuth()
          resolve(true)
        } catch (e) {
          reject(e)
        }
      })
    },
    getInfo() {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        try {
          const { user_info } = await getUserInfo()
          const { result } = await rewriteRequest({
            url: 'https://kuajing.pinduoduo.com/bg/quiet/api/mms/userInfo',
            method: 'POST'
          })
          this.userInfo = result.result || {}
          this.sysUser = user_info
          this.sysUser.bindMallIds =
            user_info.boundled_mallShops.map((m) => m.mall_id) || []
          this.roles = [user_info.user_level]
          resolve({
            roles: [user_info.user_level],
            routes: []
          })
        } catch (e) {
          reject(e)
        }
      })
    },
    getPddInfo() {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve) => {
        try {
          const { result } = await rewriteRequest({
            url: 'https://kuajing.pinduoduo.com/bg/quiet/api/mms/userInfo',
            method: 'POST'
          })
          if (result.error_code === 40001) {
            this.hasPddUser = false
            this.userInfo = {}
          } else {
            this.hasPddUser = true
            this.userInfo = result.result || {}
          }
          resolve(result.result)
        } catch (e) {
          // reject(e)
          this.hasPddUser = false
          this.userInfo = {}
          resolve({})
        }
      })
    },
    logout() {
      const tagsViewStore = useTagsViewStore()
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve) => {
        try {
          await logout()
        } catch (e) {
          //
        }
        clearInterval(this.validTokenTimer)
        this.token = ''
        this.roles = []
        removeToken()
        resetRouter()
        tagsViewStore.delAllViews()
        resolve()
      })
    },
    resetToken() {
      return new Promise((resolve) => {
        this.token = ''
        this.roles = []
        removeToken()
        resolve()
      })
    }
  }
})
